import {
  getCategory,
  getRecommendedReadingList,
  getSearchList,
} from '@/services/RecommendedReading';
import { ICategory, ILayout, ISearchList } from '@/utils/layout';
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

export interface RecommendedReadingModelState {
  list: Array<ILayout>;
  list1: Array<ICategory>;
  isSun: boolean;
  searchList: Array<ISearchList>;
}

export interface IndexModelType {
  namespace: 'RecommendedReading';
  state: RecommendedReadingModelState;
  effects: {
    getRecommendedReadingList: Effect;
    getCategory: Effect;
    changeSun: Effect;
    getSearchList: Effect;
    delSearchList: Effect;
  };
  reducers: {
    save: Reducer<RecommendedReadingModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'RecommendedReading',

  state: {
    list: [],
    list1: [],
    isSun: true,
    searchList: [],
  },
  effects: {
    *getRecommendedReadingList({ payload }, { call, put }) {
      const res = yield call(getRecommendedReadingList, { payload });
      yield put({
        type: 'save',
        payload: {
          list: res.data,
        },
      });
    },
    *getCategory({ payload }, { call, put }) {
      const res = yield call(getCategory, { payload });
      yield put({
        type: 'save',
        payload: {
          list1: res.data,
        },
      });
    },
    *getSearchList({ payload }, { call, put }) {
      const res = yield call(getSearchList, payload);
      yield put({
        type: 'save',
        payload: {
          searchList: res.data.splice(0, 10),
        },
      });
    },
    *delSearchList({ payload }, { call, put }) {
      yield put({
        type: 'save',
        payload: {
          searchList: [],
        },
      });
    },
    *changeSun({ payload }, { call, put }) {
     
      yield put({
        type: 'save',
        payload: {
          isSun: payload.isSun,
        },
      });
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default IndexModel;
